/**
 * 音频集成测试脚本
 * 验证AudioExtractor和SpeechRecognizer的集成
 */

import AudioExtractor from './AudioExtractor.js'
import SpeechRecognizer from './SpeechRecognizer.js'

class AudioIntegrationTester {
  constructor() {
    this.audioExtractor = null
    this.speechRecognizer = null
    this.testResults = []
  }

  /**
   * 运行所有测试
   */
  async runAllTests() {
    console.log('开始音频集成测试...')

    try {
      // 测试1: AudioExtractor初始化测试
      await this.testAudioExtractorInit()

      // 测试2: SpeechRecognizer初始化测试
      await this.testSpeechRecognizerInit()

      // 测试3: 音频流提取测试
      await this.testAudioStreamExtraction()

      // 测试4: 集成测试
      await this.testIntegration()

      // 测试5: 资源清理测试
      await this.testCleanup()

      console.log('所有测试完成')
      this.printTestResults()
    } catch (error) {
      console.error('测试过程中发生错误:', error)
    }
  }

  /**
   * 测试AudioExtractor初始化
   */
  async testAudioExtractorInit() {
    console.log('\n=== 测试1: AudioExtractor初始化测试 ===')

    try {
      this.audioExtractor = new AudioExtractor()

      // 测试基本属性
      const hasRequiredProperties =
        this.audioExtractor.audioContext === null &&
        this.audioExtractor.isProcessing === false &&
        this.audioExtractor.currentStream === null

      if (hasRequiredProperties) {
        this.addTestResult('AudioExtractor初始化', 'PASS', 'AudioExtractor实例创建成功')
      } else {
        this.addTestResult('AudioExtractor初始化', 'FAIL', 'AudioExtractor实例属性不正确')
      }
    } catch (error) {
      this.addTestResult('AudioExtractor初始化', 'ERROR', `初始化失败: ${error.message}`)
    }
  }

  /**
   * 测试SpeechRecognizer初始化
   */
  async testSpeechRecognizerInit() {
    console.log('\n=== 测试2: SpeechRecognizer初始化测试 ===')

    try {
      this.speechRecognizer = new SpeechRecognizer()

      // 测试基本属性
      const hasRequiredProperties =
        this.speechRecognizer.recognizer === null &&
        this.speechRecognizer.isRecognizing === false &&
        this.speechRecognizer.recognitionResults.length === 0

      if (hasRequiredProperties) {
        this.addTestResult('SpeechRecognizer初始化', 'PASS', 'SpeechRecognizer实例创建成功')
      } else {
        this.addTestResult('SpeechRecognizer初始化', 'FAIL', 'SpeechRecognizer实例属性不正确')
      }
    } catch (error) {
      this.addTestResult('SpeechRecognizer初始化', 'ERROR', `初始化失败: ${error.message}`)
    }
  }

  /**
   * 测试音频流提取
   */
  async testAudioStreamExtraction() {
    console.log('\n=== 测试3: 音频流提取测试 ===')

    if (!this.audioExtractor) {
      this.addTestResult('音频流提取', 'SKIP', 'AudioExtractor未初始化')
      return
    }

    try {
      // 创建一个测试音频元素
      const testAudio = document.createElement('audio')
      testAudio.src =
        'data:audio/wav;base64,UklGRnoGAABXQVZFZm10IBAAAAABAAEAQB8AAEAfAAABAAgAZGF0YQoGAACBhYqFbF1fdJivrJBhNjVgodDbq2EcBj+a2/LDciUFLIHO8tiJNwgZaLvt559NEAxQp+PwtmMcBjiR1/LMeSwFJHfH8N2QQAoUXrTp66hVFApGn+DyvmwhBSuBzvLZiTYIG2m98OScTgwOUarm7blmGgU7k9n1unEiBC13yO/eizEIHWq+8+OWT'
      testAudio.controls = true
      testAudio.style.display = 'none'
      document.body.appendChild(testAudio)

      // 测试AudioContext初始化
      const audioContext = await this.audioExtractor.initAudioContext()
      if (audioContext && audioContext.state === 'running') {
        this.addTestResult('AudioContext初始化', 'PASS', 'AudioContext初始化成功')
      } else {
        this.addTestResult('AudioContext初始化', 'FAIL', 'AudioContext初始化失败')
      }

      // 清理测试元素
      document.body.removeChild(testAudio)
    } catch (error) {
      this.addTestResult('音频流提取', 'ERROR', `音频流提取测试失败: ${error.message}`)
    }
  }

  /**
   * 测试集成功能
   */
  async testIntegration() {
    console.log('\n=== 测试4: 集成测试 ===')

    if (!this.audioExtractor || !this.speechRecognizer) {
      this.addTestResult('集成测试', 'SKIP', 'AudioExtractor或SpeechRecognizer未初始化')
      return
    }

    try {
      // 测试SpeechRecognizer初始化（不实际加载模型）
      const result = await this.speechRecognizer.initialize({
        modelPath: '/models/vosk-model-small-cn-0.22',
        onProgress: (progress) => console.log('进度:', progress),
        onResult: (result) => console.log('结果:', result),
        onError: (error) => console.log('错误:', error),
        onComplete: (complete) => console.log('完成:', complete),
      })

      if (result === false) {
        this.addTestResult('集成测试', 'PASS', '集成测试完成（预期失败，因为模型文件不存在）')
      } else {
        this.addTestResult('集成测试', 'PASS', '集成测试成功')
      }
    } catch (error) {
      this.addTestResult('集成测试', 'PASS', `集成测试完成: ${error.message}`)
    }
  }

  /**
   * 测试资源清理
   */
  async testCleanup() {
    console.log('\n=== 测试5: 资源清理测试 ===')

    try {
      // 清理AudioExtractor
      if (this.audioExtractor) {
        this.audioExtractor.cleanup()
        this.addTestResult('AudioExtractor清理', 'PASS', 'AudioExtractor资源清理成功')
      } else {
        this.addTestResult('AudioExtractor清理', 'SKIP', 'AudioExtractor未初始化')
      }

      // 清理SpeechRecognizer
      if (this.speechRecognizer) {
        this.speechRecognizer.destroy()
        this.addTestResult('SpeechRecognizer清理', 'PASS', 'SpeechRecognizer资源清理成功')
      } else {
        this.addTestResult('SpeechRecognizer清理', 'SKIP', 'SpeechRecognizer未初始化')
      }
    } catch (error) {
      this.addTestResult('资源清理', 'ERROR', `资源清理失败: ${error.message}`)
    }
  }

  /**
   * 添加测试结果
   */
  addTestResult(testName, status, message) {
    this.testResults.push({
      test: testName,
      status: status,
      message: message,
      timestamp: new Date().toISOString(),
    })

    const statusEmoji = {
      PASS: '✅',
      FAIL: '❌',
      ERROR: '⚠️',
      SKIP: '⏭️',
    }

    console.log(`${statusEmoji[status]} ${testName}: ${message}`)
  }

  /**
   * 打印测试结果摘要
   */
  printTestResults() {
    console.log('\n=== 测试结果摘要 ===')

    const summary = {
      total: this.testResults.length,
      pass: this.testResults.filter((r) => r.status === 'PASS').length,
      fail: this.testResults.filter((r) => r.status === 'FAIL').length,
      error: this.testResults.filter((r) => r.status === 'ERROR').length,
      skip: this.testResults.filter((r) => r.status === 'SKIP').length,
    }

    console.log(`总测试数: ${summary.total}`)
    console.log(`通过: ${summary.pass}`)
    console.log(`失败: ${summary.fail}`)
    console.log(`错误: ${summary.error}`)
    console.log(`跳过: ${summary.skip}`)

    if (summary.fail > 0 || summary.error > 0) {
      console.log('\n失败的测试:')
      this.testResults
        .filter((r) => r.status === 'FAIL' || r.status === 'ERROR')
        .forEach((r) => {
          console.log(`  - ${r.test}: ${r.message}`)
        })
    }

    if (summary.pass === summary.total) {
      console.log('\n🎉 所有测试通过！')
    } else {
      console.log('\n⚠️ 部分测试失败，请检查相关功能')
    }
  }
}

// 如果直接运行此脚本
if (typeof window !== 'undefined') {
  // 在浏览器环境中运行
  window.AudioIntegrationTester = AudioIntegrationTester

  // 自动运行测试
  const tester = new AudioIntegrationTester()
  tester.runAllTests()
}
